package com.lzc.aopcache.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 转换为json字符串
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException("序列化对象【" + object + "】时出错", e);
        }
    }

    /**
     * 将json字符串转换为对象
     *
     * @param entityClass
     * @param jsonString
     * @param <T>
     * @return
     */
    public static <T> T toBean(Class<T> entityClass, String jsonString) {
        try {
            return objectMapper.readValue(jsonString, entityClass);
        } catch (Exception e) {
            throw new RuntimeException("JSON【" + jsonString + "】转对象时出错", e);
        }
    }
}
